package com.wj.controller;

import com.wj.domain.vo.BookShelfVO;
import com.wj.service.BookShelfService;
import com.wj.tool.common.vo.WebResponse;
import com.wj.tool.utils.Result;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class BookShelfController {

    @Resource
    private BookShelfService bookShelfService;

    /**
     * 书架
     */
    @RequestMapping(value = "shelf")
    public String Shelf(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("id");
        List<BookShelfVO> list = null;
        try {
            if (userId != null && userId != 0){
                list = bookShelfService.queryByUserId(userId);
            } else {
                return "/login";
            }
            model.addAttribute("list",list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "book/book_shelf";
    }


    /**
     * 用户加入书架
     *
     * @param bookId 小说id
     * @return 成功或者失败
     */
    @ResponseBody
    @RequestMapping(value = "addShelf")
    public WebResponse AddShelf(HttpServletRequest request, @RequestParam("bookId") Long bookId) {

        int result = bookShelfService.addShelf(request, bookId);
        if (result == 1){
            return new WebResponse(200,"加入书架成功");
        } else {
            return new WebResponse(-1,"加入书架失败");
        }
    }

    /**
     *  从书架删除小说
     * @param request
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deleteShelf")
    public Result deleteShelf(HttpServletRequest request, @RequestParam("id") Long id){
        HttpSession session = request.getSession();
        if (null==session.getAttribute("id")){
            throw new DuplicateKeyException("请登录");
        }
        Long userId= (Long) session.getAttribute("id");
        int i = bookShelfService.deleteShelf(id, userId);
        if (i==0){
            return new Result(-1,"移除书架失败");
        }
        return new Result(200,"移除书架成功");
    }
}